package com.knife.common.utils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * 获取文件名
 *
 * @author： 76875
 * @date： 2022/4/6 星期三 19:00
 * @description：
 * @modifiedBy：
 * @version: 1.0
 */
public class KnifeFileNameUtil {

    public static String encodeFileName(HttpServletRequest request, String filename) throws IOException {
        filename = filename.replace(" ", "");
        filename = filename.replace("\n", "");
        filename = filename.replace("\r", "");
        if (request == null) {
            return URLEncoder.encode(filename, "UTF-8");
        } else {
            String userAgent = request.getHeader("User-Agent");
            String encodeFilename;
            if (StringUtils.isBlank(userAgent)) {
                encodeFilename = URLEncoder.encode(filename, "UTF-8");
            } else if (!userAgent.contains("MSIE") && !userAgent.contains("like Gecko")) {
                encodeFilename = "=?UTF-8?B?" + Base64.getEncoder().encodeToString(filename.getBytes(StandardCharsets.UTF_8)) + "?=";
            } else {
                encodeFilename = URLEncoder.encode(filename, "UTF-8");
            }

            return encodeFilename;
        }
    }

    public static String encodeFileName(String filename) throws IOException {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (servletRequestAttributes == null) {
            return URLEncoder.encode(filename, "UTF-8");
        } else {
            HttpServletRequest request = servletRequestAttributes.getRequest();
            return encodeFileName(request, filename);
        }
    }

    public static String getFileName(String fileUrl) {
        if (StringUtils.isBlank(fileUrl)) {
            return null;
        } else {
            try {
                int index = fileUrl.indexOf("@");
                if (index > -1) {
                    return fileUrl.substring(index + 1);
                } else {
                    String[] s = fileUrl.split("/");
                    return s.length > 1 ? s[s.length - 1] : null;
                }
            } catch (Exception var3) {
                return null;
            }
        }
    }
}
